package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.UsersHXEntity;

public class UsersHXDAO {
	public int insert(Connection conn, UsersHXEntity e) throws SQLException {
		int id = -1;
		PreparedStatement ps = conn.prepareStatement(
				"INSERT INTO users_hx ( username, password, user_id) VALUES (?,?,?)", Statement.RETURN_GENERATED_KEYS);
		ps.setString(1, e.getUsername());
		ps.setString(2, e.getPassword());
		ps.setInt(3, e.getUser_id());
		if (ps.executeUpdate() > 0) {
			ResultSet rs = ps.getGeneratedKeys();
			if (rs.next()) {
				id = rs.getInt(1);
			}
		}
		return id;
	}

	public boolean update(Connection conn, UsersHXEntity e) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn
				.prepareStatement("update users_hx set username=?, password=?, user_id=? where id =?");
		ps.setString(1, e.getUsername());
		ps.setString(2, e.getPassword());
		ps.setInt(3, e.getUser_id());
		ps.setInt(4, e.getId());
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}

	private UsersHXEntity fill(ResultSet rs) throws SQLException {
		UsersHXEntity e = new UsersHXEntity();
		e.setId(rs.getInt("id"));
		e.setUser_id(rs.getInt("user_id"));
		e.setUsername(rs.getString("username"));
		e.setPassword(rs.getString("password"));
		return e;
	}

	public UsersHXEntity findByUserId(Connection conn, int user_id) throws SQLException {
		UsersHXEntity e = null;
		PreparedStatement ps = conn.prepareStatement("select * from users_hx where user_id=?");
		ps.setInt(1, user_id);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			e = fill(rs);
		}
		return e;
	}

	public List<UsersHXEntity> list(Connection conn) throws SQLException {
		List<UsersHXEntity> list = new LinkedList<>();
		PreparedStatement ps = conn.prepareStatement("select * from users_hx");
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			UsersHXEntity e = fill(rs);
			list.add(e);
		}
		return list;
	}
}
